package com.nidu.demo.dept.executor.command;

import com.alibaba.cola.dto.SingleResponse;
import com.nidu.demo.company.ability.CompanyDomainService;
import com.nidu.demo.company.gateway.CompanyGateway;
import com.nidu.demo.dept.ability.DepartmentDomainService;
import com.nidu.demo.dept.convertor.DepartmentConvertor;
import com.nidu.demo.dept.dto.DepartmentAddCmd;
import com.nidu.demo.dept.dto.DepartmentCO;
import com.nidu.demo.dept.gateway.DepartmentGateway;
import com.nidu.demo.dept.model.Department;
import com.nidu.demo.dept.util.DepartmentUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 部门创建命令执行器
 *
 * @author auto
 */
@Component
@RequiredArgsConstructor
public class DepartmentAddCmdExe {

    private final DepartmentGateway gateway;

    private final DepartmentDomainService domainService;

    private final DepartmentConvertor convertor;

    private final CompanyDomainService companyDomainService;

    public SingleResponse<DepartmentCO> execute(DepartmentAddCmd cmd) {
        // 1. 转换为领域对象
        Department dept = Department.create(cmd.getDeptName(), cmd.getDeptCode(), cmd.getParentId(), 
                cmd.getCompanyId(), cmd.getRemark(), cmd.getSortOrder(),
                cmd.getLeader(), cmd.getPhoneNumber(), cmd.getEmail());

        // 2.检查公司是否存在
        companyDomainService.validateCompany(dept.getCompanyId());
        // 3.检查对象是否已存在
        domainService.validateDuplicate(dept.getDeptCode(), dept.getCompanyId(), dept.getId());
        // 4.检查父部门是否存在或者启用
        Department parent = domainService.validateParent(dept.getParentId());
        // 4.拼接祖先节点
        String ancestors = DepartmentUtil.buildAncestors(dept.getParentId(), parent);
        dept.setAncestors(ancestors);

        // 4. 调用网关保存
        Department save = gateway.create(dept);

        // 5. 转换为DTO返回
        DepartmentCO deptCO = convertor.toClientObject(save);

        return SingleResponse.of(deptCO);
    }
} 